package com.xuecheng.auth.controller;

import com.xuecheng.api.auth.AuthControllerApi;
import com.xuecheng.auth.service.AuthService;
import com.xuecheng.framework.domain.ucenter.ext.AuthToken;
import com.xuecheng.framework.domain.ucenter.request.LoginRequest;
import com.xuecheng.framework.domain.ucenter.response.JwtResult;
import com.xuecheng.framework.domain.ucenter.response.LoginResult;
import com.xuecheng.framework.exception.CustomExcetionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/")
public class AuthController implements AuthControllerApi {
    @Autowired
    AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;


    /**
     * @Description: 登录认证
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    @PostMapping("/userlogin")
    @Override
    public LoginResult login(LoginRequest loginRequest) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        String verifycode = loginRequest.getVerifycode();
        verifycode = "1";
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(verifycode)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);
//      将令牌存入cookie中
        saveCookie(authToken.getJwt_token(), cookieMaxAge);
        return new LoginResult(CommonCode.SUCCESS, authToken.getJwt_token());
    }

    /**
     * @Description: 用户退出
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    @PostMapping("/userlogout")
    @Override
    public ResponseResult logout() {
//    设置cookie过期时间为0
        String cookie = getCookie();
        if(StringUtils.isEmpty(cookie)){
            return new ResponseResult(CommonCode.FAIL);
        }
        saveCookie(cookie, 0);
        return authService.logout(cookie);
    }


    /**
     * @Description: 获取cookie中jwt令牌
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    @GetMapping("/userjwt")
    @Override
    public JwtResult getJwt() {
        String s = getCookie();
        return authService.getJwt(s);
    }


    /**
     * @Description: 将令牌存入redis
     * @Param: jwt_token
     * @return: void
     * @Author: Mr.Yuan
     * @Date:
     */
    private void saveCookie(String jwt_token, int time) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jwt_token, time, false);
    }

    /**
     * @Description: 从请求中获取cookie
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private String getCookie() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> map = CookieUtil.readCookie(request, "uid");
        String uid = map.get("uid");
        if(StringUtils.isEmpty(uid)){
            return null;
        }
        return uid;
    }


}
